package com.fpf.controller.advice;

import com.fpf.controller.vo.response.APIException;
import com.fpf.controller.vo.response.ResultCode;
import com.fpf.controller.vo.response.ResultVO;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 统一参数异常处理
 * 针对form-data格式的数据传输，进行的数据参数校验
 */
@RestControllerAdvice("com.fpf.controller")
public class ExceptionAdvice {
    //拦截BindException
    @ExceptionHandler({BindException.class})
    public ResultVO requestParamExceptionHandler(BindException e){
        System.out.println(e.getMessage());
        // 从异常对象中拿到ObjectError对象
        List<ObjectError> allErrors=e.getBindingResult().getAllErrors();
        List<String> errors=allErrors.stream().map(ObjectError::getDefaultMessage).collect(Collectors.toList());
        return new ResultVO(ResultCode.VALIDATE_ERROR, String.join(",",errors));
    }
    //拦截APIException
    @ExceptionHandler({APIException.class})
    public ResultVO apiExceptionHandler(APIException e){
        return new ResultVO(e.getCode(), e.getMsg(), e.getMessage());
    }
}
